package kzy.controller;

import kzy.common.R;
import kzy.entiy.mailbox;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 验证码控制器
 * @Author 大溪地
 * @create 2023年06月13日16:20
 */
@Slf4j
@RestController
@RequestMapping("/captchaController")
public class CaptchaController {
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private JavaMailSender mailSender;
	//	获取了发送的人的邮箱地址
	@Value("${spring.mail.username}")
	private String emailFrom;
	/**
	 * 获取验证码
	 * @param mailbox
	 * @return
	 */
	@PostMapping("")
	public R<String> sendEmail(@RequestBody mailbox mailbox){
		try {
// 		生成验证码
			Random random = new Random();
			int code = random.nextInt(99999999 - 10000000 + 1) + 10000000;
			String verificationCode = String.valueOf(code);
			System.out.println(verificationCode);
			String verificationCode1 =(verificationCode.substring(0,4)+"-"+verificationCode.substring(verificationCode.length()-4));
//		发送邮件
			SimpleMailMessage message = new SimpleMailMessage();
			message.setFrom(emailFrom);
			message.setTo(mailbox.getMailbox()+"@qq.com"); // 设置收件人邮箱地址
			message.setSubject("验证码"); // 设置邮件主题
			message.setText(verificationCode1); // 设置邮件内容
			mailSender.send(message); // 发送邮件
// 		设置缓存
			redisTemplate.opsForValue().set(mailbox.getMailbox()+"@qq.com", verificationCode, 600L, TimeUnit.SECONDS);
			return R.success("验证码发送成功10分钟内有效");
		} catch (MailException e) {
			return R.error("服务器发送了一个错误，可能是您的QQ号码不正确");
		}

	}

}
